package com.u2b.db.datasource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.u2b.global.utils.Constants;

public class MyBeanUtils
{
    public void setPropertiesFromMap(Map<String, Object> values, Object bean)
    {
        Iterator<String> iterable = values.keySet().iterator();
        try
        {
            while (iterable.hasNext())
            {
                String key = iterable.next();
                BeanUtils.setProperty(bean, key, values.get(key));
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("Map对象解析解析成一个Bean对象的时候出现错误", e);
        }

    }

    public <T> List<T> setPropertiesFromList(List<HashMap<String, Object>> result, String clazzName)
    {
        T bean = null;
        List<T> beanList = new ArrayList<T>();
        clazzName = Constants.beansPackgeName + clazzName;
        try
        {
            for (HashMap<String, Object> value : result)
            {
                bean = (T) Class.forName(clazzName).newInstance();
                setPropertiesFromMap(value, bean);
                beanList.add(bean);
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("从list<HashMap<String,Object>>中对象解析错误", e);
        }

        return beanList;
    }
}
